package org.dingyom.gift.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.dingyom.gift.exception.BusinessException;
import org.dingyom.gift.exception.code.StatusCode;
import org.dingyom.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice //通知
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        log.error("error occurs！"+e.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(e.getCode()).setMessage(e.getMessage());
    }

    /**
     * 其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        /*log.error("error occurs！"+e.getMessage());
        StatusCode code = StatusCode.CODE_500;
        return AjaxResult.me().setSuccess(false).setCode(code.getCode()).setMessage(code.getMessage());*/
        String className = e.getClass().getCanonicalName();
        if (className.endsWith("AccessDeniedException")){ //没有权限特殊处理
            StatusCode code = StatusCode.CODE_403_FORBIDDEN_ACCESS;
            return AjaxResult.me().setSuccess(false).setCode(code.getCode())
                    .setMessage(code.getMessage());
        }
        StatusCode code = StatusCode.CODE_500;
        e.printStackTrace();
        log.error("error occurred!"+e.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(code.getCode())
                .setMessage(code.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();//获取所有错误
        StringBuilder sb = new StringBuilder();
        allErrors.forEach(error -> {
            String defaultMessage = error.getDefaultMessage();
            sb.append(defaultMessage+",");//将错误凭借成字符串 逗号隔开
        });
        String error = sb.substring(0, sb.length() - 1);//删除最后一个逗号
        log.error(error);
        return AjaxResult.me().setSuccess(false).setCode(StatusCode.CODE_400.getCode()).setMessage(error);
    }
}
